<script setup lang="ts">
import useSettingStore from "@/store/modules/setting.ts";
import {nextTick, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import type {TabPaneName, TabsPaneContext} from "element-plus";
const settingStore = useSettingStore();
const $route = useRoute();
const $router = useRouter();
// 控制路由组件是否进行呈现
const isRender = ref<boolean>(true);
// 绑定切换面板的数据
const editableTabs = ref([
    {
        title: '主页',
        name: '/',
        closable:false
    }
])
// 侦听路由地址是否发生更改，如果更改了，那么操作editableTabs
watch(()=>$route.path,()=>{
    // 判断editableTabs是否已经存在当前的路由？
    // 存在：不需要添加
    // 不存在：添加路由信息至editableTabs
    if(!editableTabs.value.some(item=>item.name===$route.path)){
        editableTabs.value = [
            ...editableTabs.value,
            {
                title:$route.meta.title as string,
                name:$route.path,
                closable:true
            }
        ]
    }
},{
    immediate:true
});
// 第一个参数为函数，侦听该函数的返回值是否有变化
watch(()=>settingStore.isRefresh,()=>{
    isRender.value = false;
    nextTick(()=>{
        isRender.value = true;
    });
});
const removeHandler = function(name:TabPaneName){
    const index = editableTabs.value.findIndex(item=>item.name===name);
    if(index>-1){
        // 删除
        editableTabs.value = editableTabs.value.filter(item=>item.name!==name);
        // 删除的tab->name是否与当前路由$route.path 一致
        if(name === $route.path){
            $router.push(editableTabs.value[index-1].name)
        }
    }

}
// 点击面板触发的函数
const clickHandler = function(pane:TabsPaneContext){
    $router.push(pane.paneName as string);
}
defineOptions({
    name:"Main"
})
</script>

<template>
    <el-tabs
        :model-value="$route.path"
        type="card"
        class="demo-tabs"
        @tab-remove="removeHandler"
        @tab-click="clickHandler"
    >
        <el-tab-pane
            v-for="item in editableTabs"
            :key="item.name"
            :label="item.title"
            :name="item.name"
            :closable="item.closable"

        >
        </el-tab-pane>
    </el-tabs>
    <el-scrollbar style="height:calc(100vh - 105px)">
        <el-card>
            <router-view v-if="isRender"/>
        </el-card>
    </el-scrollbar>

</template>

<style scoped lang="less">
:deep(.el-tabs__header){
    height:auto;
    margin-bottom: 5px;
}
:deep(.el-card__body){
    padding:5px;
}
:deep(.el-table__inner-wrapper){
    z-index: 0;
}
</style>